﻿using Core.Configuration.Config;
using IP2Region.Net.XDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Text;

namespace Core.Configuration.Api
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ApiBase : ControllerBase
    {

        #region 获取header参数
        protected int GetStoreId()
        {
            var store_id = GetHeaderInt("storeid");
            return store_id <= 0 ? 1 : store_id;
        }
        /// <summary>
        /// 登录会员token
        /// </summary>
        protected string GetToken()
        {
            return GetHeader("Access_Token");
        }
        /// <summary>
        /// 登录会员token
        /// </summary>
        protected int GetTokenUid()
        {
            var user_id = GetHeaderInt("user_id");
            return user_id;
        }
        /// <summary>
        /// 客户端（APP、小程序、H5等）
        /// </summary>
        protected string GetPlatform()
        {
            return GetHeader("platform");
        }
        protected int GetHeaderInt(string name)
        {
            if (Request.Headers == null) return 0;

            var value = Request.Headers[name];
            if (string.IsNullOrEmpty(value)) return 0;
            return Convert.ToInt32(value);
        }
        protected string GetHeader(string name)
        {
            var value = Request.Headers[name];
            if (string.IsNullOrEmpty(value)) return string.Empty;
            return value;
        }
        #endregion

        /// <summary>
        /// 客户端IP
        /// </summary>
        /// <returns></returns>
        protected string GetIP()
        {
            string ip = string.Empty;
            if (Request.Headers.ContainsKey("X-Forwarded-For"))
            {
                ip = Request.Headers["X-Forwarded-For"];
            }
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            }
            if (ip.Contains("0.0.0.1"))
            {
                ip = "127.0.0.1";
            }
            return ip;
        }

        /// <summary>
        /// 获取IP归属地,格式：中国广东省深圳市
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        protected string GetIpLocation(string ip)
        {
            if (string.IsNullOrEmpty(GlobalConfig.IpFilePath))
                throw new Exception("未配置IP归属文件路径，路径节点格式：GlobalConfig/IpFilePath");

            if (!string.IsNullOrEmpty(ip))
            {
                var ipSearch = new Searcher(CachePolicy.Content, GlobalConfig.IpFilePath);
                //IP所在地，格式：中国|0|浙江省|杭州市|阿里云
                var ipArray = ipSearch.Search(ip).Split('|');
                if (ipArray.Length >= 3 && ipArray[3] !="0")
                    return $"{ipArray[0]}{ipArray[2]}{ipArray[3]}";
            }
            
            return string.Empty;
        }
        /// <summary>
        /// 获取post请求的主体参数
        /// </summary>
        /// <returns></returns>
        protected string GetBody()
        {
            var body = string.Empty;
            using (var stream = new StreamReader(Request.Body))
            {
                body = stream.ReadToEndAsync().GetAwaiter().GetResult();
            }
            return body;
        }
        protected string GetAbsoluteUri(HttpRequest request)
        {
            return new StringBuilder()
             .Append(request.Scheme)
             .Append("://")
             .Append(request.Host)
             .Append(request.PathBase)
             .Append(request.Path)
             .Append(request.QueryString)
             .ToString();
        }

        protected void CheckEmpty(string str,string errMsg)
        {
            if (string.IsNullOrEmpty(str))
                throw new Exception(errMsg);
        }                
    }
}